package com.app.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

/**
 * 图片处理
 * @author yinhuadong
 *
 */
public class ImageUtils {
	
	/**
	 * 从远程网络访问图片
	 * @param url
	 * @return
	 */
	public Bitmap returnBitMap(String url){
		URL rpcUrl = null;
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			rpcUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			HttpURLConnection conn = (HttpURLConnection) rpcUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return bitmap;
	}
	
	/**
	 * 缩放图片
	 * @param bitmap
	 * @param w
	 * @param h
	 * @return
	 */
	public static Drawable imageResize(Bitmap bitmap,int w,int h){
		Bitmap bitmapOrg = bitmap;
		
		int width = bitmapOrg.getWidth();
		int height = bitmapOrg.getHeight();
		
		int newWidth = w;
		int newHeight = h;
		
		float scaleWidth = (float)(newWidth / width);
		float scaleHeight = (float)(newHeight / height);
		
		Matrix mx = new Matrix();
		mx.postScale(scaleWidth, scaleHeight);
		
		Bitmap resizeBitmap = Bitmap.createBitmap(bitmapOrg, width, height,
				newWidth, newHeight, mx, true);
		
		return new BitmapDrawable(resizeBitmap);
	}
	
	/**
	 * 根据资源id获取bitmap
	 * @param context
	 * @param bitAdress
	 * @return
	 */
	public static Bitmap createImage(Context context,int bitAdress){
		Bitmap bitmap = null;
		bitmap = BitmapFactory
				.decodeResource(context.getResources(), bitAdress);
		return bitmap;
	}
	
}
